package com.lancoo.answer.ui.answerSheet;

import android.app.Dialog;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lancoo.answer.R;
import com.lancoo.answer.helper.SubmitConfirmDialogHelper;
import com.lancoo.answer.model.AnswerConstant;
import com.lancoo.answer.model.ConstantBean;
import com.lancoo.answer.model.TaskState;
import com.lancoo.answer.model.bean.Type;
import com.lancoo.answer.model.entity.AnswerSheetBean;
import com.lancoo.answer.model.entity.TaskControlBean;
import com.lancoo.answer.model.eventBean.AnswerSheetEventBean;
import com.lancoo.answer.model.eventBean.SubmitConfirmDialogShowEventBean;
import com.lancoo.answer.model.eventBean.SubmitEventBean;
import com.lancoo.answer.ui.paper.PaperFragment;
import com.lancoo.answer.util.paperUtils.PaperDataUtils;
import com.lancoo.answer.widget.combinationView.TestRequirementView;
import com.rxjava.rxlife.RxLife;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Single;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import kotlin.Triple;

/**
 * Created by pengmi on 2021/6/7 15:46
 * Description:答题卡dialog
 */
public class AnswerSheetDialog extends BottomSheetDialogFragment {

    public static final String TAG = "AnswerSheetDialog";
    private int currentTypeIndex,currentQuesIndex,currentChildIndex,currentItemIdex;
    private RecyclerView recyclerView;
    private int scrollIndex=0,totalChildCount,totalUnAnswerCount;

    @Override
    public void onStart() {
        super.onStart();
        Log.e(TAG, "onStart: " );
        Dialog dialog = getDialog();
        if (dialog != null&& getActivity()!=null&&dialog.getWindow()!=null) {
            DisplayMetrics dm = new DisplayMetrics();
            getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
            int width = dm.widthPixels; //设置宽度
            int height = dm.heightPixels;
            TaskControlBean taskControlBean = ConstantBean.Companion.getTaskControlBean();
            if(taskControlBean!=null&&taskControlBean.getAnswerSheetDialogHeight()>0&&
                height>=taskControlBean.getAnswerSheetDialogHeight()){
                height=taskControlBean.getAnswerSheetDialogHeight();
            }
            dialog.getWindow().setLayout( width, height);
            dialog.getWindow().setGravity(Gravity.BOTTOM);
            Window window = dialog.getWindow();
            WindowManager.LayoutParams attributes = window.getAttributes();
            attributes.dimAmount=0.7f;
            window.setAttributes(attributes);
        }
        final View view = getView();
        if(view==null){
            return;
        }
        view.post(() -> {
            View parent = (View) view.getParent();
            CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) (parent).getLayoutParams();
            if(params!=null){
                CoordinatorLayout.Behavior behavior = params.getBehavior();
                if(behavior instanceof BottomSheetBehavior){
                    BottomSheetBehavior bottomSheetBehavior = (BottomSheetBehavior) behavior;
                    bottomSheetBehavior.setPeekHeight(view.getMeasuredHeight());
                }
            }
        });
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        return super.onCreateDialog(savedInstanceState);

    }


    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Log.e(TAG, "onCreateView: " );
        if(!(getDialog()==null|| getDialog().getWindow()==null)){
            getDialog().getWindow().getAttributes().windowAnimations = R.style.answerSheet_DialogAnimation;
        }
        View convertView = inflater.inflate(R.layout.ev_fragment_dialog_answer_sheet, container, false);
        initView(convertView);
        getDialog().setOnCancelListener(null);
        return convertView;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.e(TAG, "onCreate: " );
        setStyle(DialogFragment.STYLE_NORMAL, R.style.answerSheet_ColorStyle);
    }


    private void initView(View view){

        if(getArguments()==null){
            return;
        }
        TaskControlBean taskControlBean = ConstantBean.getTaskControlBean();
        if(taskControlBean==null){
            return;
        }
        TextView tv_title=view.findViewById(R.id.tv_card_title);
        tv_title.setText(ConstantBean.getTaskControlBean().isHp()?R.string.ev_huping_sheet:R.string.ev_answer_sheet);
        currentTypeIndex=getArguments().getInt(AnswerConstant.KEY_TYPEINDEX);
        currentQuesIndex=getArguments().getInt(AnswerConstant.KEY_QUESINDEX);
        currentChildIndex=getArguments().getInt(AnswerConstant.KEY_CHILDINDEX);
        currentItemIdex=getArguments().getInt(AnswerConstant.KEY_ITEMINDEX);
        recyclerView = view.findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        int kindType=getArguments().getInt(AnswerConstant.KEY_KINDTYPE);
        int trainSence = taskControlBean.getTrainSence();
        int paperType = taskControlBean.getPaperType();
        if(paperType==2){
            trainSence=1;
        }
        final int trainSenceCopy=trainSence;

        Observable.create((ObservableOnSubscribe<List<AnswerSheetBean>>) emitter -> {
                    ConstantBean.Companion.setOnClickSubTime(System.currentTimeMillis());
                    List<AnswerSheetBean> answerSheetBeanList=new ArrayList<>();
                    List<AnswerSheetBean> answerSheetList = ConstantBean.getAnswerSheetList();
                    if(answerSheetList!=null){
                        answerSheetBeanList.addAll(answerSheetList);
                    }else{
                        Log.e("dialog","init currentItemIdex:"+currentItemIdex);
                        Triple<Integer,Integer,Integer> triple=
                                PaperDataUtils.loadAnswerSheetData(answerSheetBeanList,currentTypeIndex,currentQuesIndex,
                                        currentChildIndex,currentItemIdex,kindType);
                        scrollIndex=triple.component1();
                        totalUnAnswerCount=triple.component2();
                        totalChildCount=triple.component3();

                    }
                    emitter.onNext(answerSheetBeanList);
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
            .as(RxLife.as(this))
            .subscribe(answerSheetBeanList -> {
                AnswerSheetAdapter mAdapter=new AnswerSheetAdapter(answerSheetBeanList,trainSenceCopy);
                mAdapter.setOnCallBack(bean -> {
                    if(getParentFragment() instanceof PaperFragment){
                        ((PaperFragment)getParentFragment()).onMessageEventMainThread(bean);
                    }
                });
                recyclerView.setAdapter(mAdapter);
                autoScrollToHeight();
            });
        view.findViewById(R.id.tv_cancel).setOnClickListener(v -> dismiss());
        view.findViewById(R.id.tv_sure).setOnClickListener(v -> {
            //全部做了或者是考试场景，公共试题内部不给确认提交弹窗
            if(ConstantBean.Companion.getTaskState()==TaskState.LOOKING||
                    ConstantBean.Companion.getTaskState()==TaskState.ORIGINAL){
                if(!taskControlBean.isHp()){
//                    dismissAllowingStateLoss();
                    dismiss();
                    return;
                }
            }
            if(totalUnAnswerCount==0||trainSenceCopy!=0){
                ConstantBean.Companion.setOnClickSubTime(System.currentTimeMillis());
                SubmitEventBean eventBean=new SubmitEventBean();
                eventBean.setTotalChildCount(totalChildCount);
                eventBean.setTotalChildUnAnswerCount(totalUnAnswerCount);
                EventBus.getDefault().post(eventBean);
            }else{
                SubmitConfirmDialogShowEventBean eventBean=new SubmitConfirmDialogShowEventBean();
                eventBean.setShowState(0);
                EventBus.getDefault().post(eventBean);
                SubmitConfirmDialogHelper.showConfirmDialog(getContext(), totalUnAnswerCount, new SubmitConfirmDialogHelper.SubmitConfirCallBack() {
                    @Override
                    public void onSure() {
                        super.onSure();
                        ConstantBean.Companion.setOnClickSubTime(System.currentTimeMillis());
                        SubmitEventBean eventBean=new SubmitEventBean();
                        eventBean.setTotalChildCount(totalChildCount);
                        eventBean.setTotalChildUnAnswerCount(totalUnAnswerCount);
                        EventBus.getDefault().post(eventBean);
                    }

                    @Override
                    public void onCancel() {
                        SubmitConfirmDialogShowEventBean eventBean=new SubmitConfirmDialogShowEventBean();
                        eventBean.setShowState(1);
                        EventBus.getDefault().post(eventBean);
                    }
                });
            }

        });
        view.findViewById(R.id.tv_sure).setVisibility(View.VISIBLE);
        view.findViewById(R.id.tv_cancel).setVisibility(View.VISIBLE);
        if(ConstantBean.getTaskState()!= TaskState.TRAINING){
            view.findViewById(R.id.tv_sure).setVisibility(View.VISIBLE);
            view.findViewById(R.id.tv_cancel).setVisibility(View.VISIBLE);
            TextView tv_sure = view.findViewById(R.id.tv_sure);
            if(!taskControlBean.isHp()){
                tv_sure.setText("确认");
            }

        }
        if(taskControlBean.getIsCloseAnswerSheetSubmitBtn()==0){
            view.findViewById(R.id.tv_sure).setVisibility(View.GONE);
        }
        if(trainSenceCopy!=0){
            TextView tv_sure=view.findViewById(R.id.tv_sure);
            tv_sure.setText("交卷");
        }
        if(!TextUtils.isEmpty(taskControlBean.getAnswerSheetName())){
            tv_title.setText(taskControlBean.getAnswerSheetName());
        }
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                scrollIndex+=dy;
            }
        });
        TestRequirementView tqv_head=view.findViewById(R.id.tqv_head);
        if(trainSenceCopy!=0){
            tqv_head.setData();
            tqv_head.setVisibility(View.VISIBLE);
        }
        Log.e(TAG, "initView: trainSence："+trainSenceCopy);
    }

    private void autoScrollToHeight(){
        Observable.timer(200, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .as(RxLife.as(this))
                .subscribe(aLong -> {
                    if(getArguments()==null){
                        return;
                    }
                    if (recyclerView != null) {
                        recyclerView.smoothScrollToPosition(scrollIndex);
                    }
                });

    }

    public static void launchAnswerSheetDialog(FragmentManager fragmentManager,
                                               int typeIndex, int quesIndex,
                                               int childIndex, int itemIndex, int scrollY,int height,int kindType){
        if(fragmentManager==null){
            return;
        }
        if(System.currentTimeMillis()-ConstantBean.Companion.getOnClickSubTime()<1500){
            return;
        }
        ConstantBean.Companion.setOnClickSubTime(System.currentTimeMillis());
        Log.e(TAG, "typeIndex: "+typeIndex );
        Log.e(TAG, "quesIndex: "+quesIndex );
        Log.e(TAG, "childIndex: "+childIndex );
        Log.e(TAG, "itemIndex: "+itemIndex );
        AnswerSheetDialog fragment=new AnswerSheetDialog();
        Bundle mBundle=new Bundle();
        mBundle.putInt(AnswerConstant.KEY_TYPEINDEX,typeIndex);
        mBundle.putInt(AnswerConstant.KEY_QUESINDEX,quesIndex);
        mBundle.putInt(AnswerConstant.KEY_CHILDINDEX,childIndex);
        mBundle.putInt(AnswerConstant.KEY_ITEMINDEX,itemIndex);
        mBundle.putInt(AnswerConstant.KEY_SCROLLY,scrollY);
        mBundle.putInt(AnswerConstant.KEY_HEIGHT,height);
        mBundle.putInt(AnswerConstant.KEY_KINDTYPE,kindType);
        fragment.setArguments(mBundle);
        fragment.show(fragmentManager.beginTransaction(),TAG);

    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }


    public int getScrollY(){
        return scrollIndex;
    }


}
